﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace VSSTQH.DataAccess
{
    public class PODAO : BaseDataAccess, IPODAO
    {
        IList<POModel> IPODAO.GetBy(decimal inbound, int potype)
        {
            IList<POModel> collection = null;//new List<UserModel>(); 
            try
            {
                using (VssTqhDataContext biocode = new VssTqhDataContext(base.ConnectionString))
                {
                    // Get collection
                    var query = biocode.POs.
                        Where(q => q.Inbound == inbound && 
                            q.POType == potype &&
                            (q.FirstWeight == 0 || q.SecondWeight == 0)).ToList();

                    // If exists least one record.
                    if (query != null && query.Count > 0)
                    {
                        POModel model;
                        collection = new List<POModel>();
                        foreach (var entity in query)
                        {
                            model = POMapper.ToModel(entity);
                            model.IsNew = false;
                            model.IsEdit = false;
                            collection.Add(model);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Get all failed
                Debug.WriteLine(ex.Message);
            }

            return collection;
        }

        IList<POModel> IPODAO.GetBy(decimal inbound, int potype, bool isHas2ScaleTimes)
        {
            IList<POModel> collection = null;//new List<UserModel>(); 
            try
            {
                using (VssTqhDataContext biocode = new VssTqhDataContext(base.ConnectionString))
                {
                    // Get collection
                    var query = biocode.POs.
                        Where(q => q.Inbound == inbound &&
                            q.POType == potype &&
                            (q.FirstWeight > 0 && q.SecondWeight > 0)).OrderBy(q => q.FirstTime).ToList();

                    // If exists least one record.
                    if (query != null && query.Count > 0)
                    {
                        POModel model;
                        collection = new List<POModel>();
                        foreach (var entity in query)
                        {
                            model = POMapper.ToModel(entity);
                            model.IsNew = false;
                            model.IsEdit = false;
                            collection.Add(model);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Get all failed
                Debug.WriteLine(ex.Message);
            }

            return collection;
        }

        bool IPODAO.Save(POModel item, ref bool isNew)
        {
            bool result = false;
            try
            {
                using (VssTqhDataContext biocode = new VssTqhDataContext(base.ConnectionString))
                {
                    // Get single entity from database
                    var entity = biocode.POs.Where(q => q.POKey == item.POKey).SingleOrDefault();

                    if (entity != null)
                    {
                        if (item.SecondTime.HasValue && item.SecondWeight > 0 && (item.POCode == "000" || item.POCode == "---"))
                        {
                            int maxID = 1;
                            var queryMaxID = biocode.POs.Where(p => p.SecondTime.HasValue && p.SecondTime.Value.Date == DateTime.Today).Max(p => p.POCode);
                            if (queryMaxID != null)
                            {
                                if (Int32.TryParse(queryMaxID, out maxID))
                                    maxID++;
                            }
                            item.POCode = maxID.ToString().PadLeft(3, '0');
                        }

                        item.ModifiedByID = Common.UserLogin.Username;
                        item.ModifiedDate = DateTime.Now;

                        // Update entity value
                        POMapper.ToEntity(entity, item);
                        isNew = false;
                    }
                    else
                    {
                        if (item.SecondTime.HasValue && item.SecondWeight > 0)
                        {
                            int maxID = 1;
                            var queryMaxID = biocode.POs.Where(p => p.SecondTime.HasValue && p.SecondTime.Value.Date == DateTime.Today).Max(p => p.POCode);
                            if (queryMaxID != null)
                            {
                                if (Int32.TryParse(queryMaxID, out maxID))
                                    maxID++;
                            }
                            item.POCode = maxID.ToString().PadLeft(3, '0');
                        }
                        else
                        {
                            item.POCode = "---";
                        }

                        item.CreatedByID = Common.UserLogin.Username;
                        item.CreationDate = DateTime.Now;
                        item.ModifiedByID = Common.UserLogin.Username;
                        item.ModifiedDate = DateTime.Now;
                        

                        // New entity and set value to it
                        entity = new PO();
                        POMapper.ToEntity(entity, item);

                        // Execute Insertion
                        biocode.POs.InsertOnSubmit(entity);

                        isNew = true;
                    }
                    // Execute Updated
                    biocode.SubmitChanges();

                    // Update successful
                    result = true;
                    item.IsNew = false;
                    item.IsEdit = false;
                }
            }
            catch (Exception ex)
            {
                // Update failed
                Debug.WriteLine(ex.Message);
                throw ex;
            }

            return result;
        }
        #region IPODAO Members

        #endregion

        #region IBaseDataAccess<POModel> Members

        public POModel SearchObject
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public IList<POModel> Search()
        {
            throw new NotImplementedException();
        }

        public IList<POModel> Search(DateTime fromDate, DateTime toDate, string vendorID, string productID, int poType, string vehicleID, string poID)
        {
            IList<POModel> collection;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                IQueryable<PO> query = dataContext.POs.Where(q => q.SecondTime >= fromDate.Date && q.SecondTime < toDate.Date.AddDays(1));
                if (!String.IsNullOrEmpty(vendorID))
                {
                    query = query.Where(e => e.VendorID == vendorID);
                }
                if (!String.IsNullOrEmpty(productID))
                {
                    query = query.Where(e => e.ProductID == productID);
                }
                if (!String.IsNullOrEmpty(vehicleID))
                {
                    query = query.Where(e => e.VehicleID == vehicleID);
                }
                if (poType > 0)
                {
                    query = query.Where(e => e.POType == poType);
                }
                if (!String.IsNullOrEmpty(poID))
                {
                    query = query.Where(e => e.PoID.Contains(poID));
                   
                }

                collection = new List<POModel>();
                foreach (var item in query)
                {
                    collection.Add(POMapper.ToModel(item));
                }
            }

            return collection;
        }

        public IList<POModel> SortSearch(DateTime fromDate, DateTime toDate,  int poType, int sort)
        {
            IList<POModel> collection;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                IQueryable<PO> query = dataContext.POs.Where(q => q.SecondTime >= fromDate.Date && q.SecondTime < toDate.Date.AddDays(1));
               
                if (poType > 0)
                {
                    query = query.Where(e => e.POType == poType);
                }
                
                if (sort == 1)
                {
                    query = query.OrderBy(e => e.SecondTime);
                }
                else if (sort == 2)
                {
                    query = query.OrderBy(e => e.ProductID);
                }
                else if (sort == 3)
                {
                    query = query.OrderBy(e => e.VendorID);

                }
                else if (sort == 4)
                {
                    query = query.OrderBy(e => e.PoID);
                }
                else if (sort == 5)
                {
                    query = query.OrderBy(e => e.ActualWeight);
                }
                else if (sort == 6)
                {
                    query = query.OrderBy(e => e.WBS);
                }
                collection = new List<POModel>();
                foreach (var item in query)
                {
                    collection.Add(POMapper.ToModel(item));
                }
            }

            return collection;
        }


        public POModel GetLast()
        {
            throw new NotImplementedException();
        }

        public IList<POModel> GetAll()
        {
            throw new NotImplementedException();
        }

        public IList<POModel> GetAllActive()
        {
            throw new NotImplementedException();
        }

        public bool Add(POModel item)
        {
            throw new NotImplementedException();
        }

        public bool Add(IList<POModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        public bool Edit(POModel item)
        {
            throw new NotImplementedException();
        }

        public bool Edit(IList<POModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        public bool Save(IList<POModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Delete Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Delete(POModel item)
        {
            bool result = false;
            try
            {
                using (VssTqhDataContext biocode = new VssTqhDataContext(base.ConnectionString))
                {
                    // Get entity from database
                    PO entity = biocode.POs.Where(e => e.POKey == item.POKey).SingleOrDefault();

                    // Check exist
                    if (entity != null)
                    {
                        // Execute deletion
                        biocode.POs.DeleteOnSubmit(entity);
                        biocode.SubmitChanges();

                        // Delete successful
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                // Delete failed
                Debug.WriteLine(ex.Message);
            }

            return result;
        }

        public bool Delete(IList<POModel> collection, out int success, out int failed)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IPODAO Members


        public IList<ProductModel> GetProducts()
        {
            IList<ProductModel> collection = null;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                IQueryable<ProductModel> query = dataContext.POs.GroupBy(g => new { g.ProductID, g.ProductName })
                    .Select(c => new ProductModel() { ProductID = c.Key.ProductID, ProductName = c.Key.ProductName });
            }

            return collection;
        }

        public IList<VendorModel> GetVendors()
        {
             IList<VendorModel> collection = null;
            using (VssTqhDataContext dataContext = new VssTqhDataContext(base.ConnectionString))
            {
                IQueryable<VendorModel> query = dataContext.POs.GroupBy(g => new { g.VendorID, g.VendorName })
                    .Select(c => new VendorModel() { VendorID = c.Key.VendorID, VendorName = c.Key.VendorName });
            }

            return collection;
        }

        #endregion
    }
}
